package com.breakfast.fun.ui.home.product;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.R;
import com.breakfast.fun.adapter.home.SpecialProductAdapter;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.dao.DaoMaster;
import com.breakfast.fun.dao.ProductCartDao;
import com.breakfast.fun.data.entity.home.Product;
import com.breakfast.fun.data.entity.home.ProductClasses;
import com.breakfast.fun.data.entity.home.product.ProductDetail;
import com.breakfast.fun.data.entity.home.product.ProductState;
import com.breakfast.fun.data.entity.home.product.WeekdayState;
import com.breakfast.fun.ui.user.cart.UserCartActivity;
import com.breakfast.fun.util.DensityUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.T;
import com.breakfast.fun.view.widget.BookCountDown;
import com.breakfast.fun.view.widget.CustomGridView;
import com.breakfast.fun.view.widget.ObservableScrollView;
import com.breakfast.fun.view.widget.ScrollViewListener;
import com.breakfast.fun.view.widget.TitleBarView;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;

public class SpecialProductActivity extends BaseActivity<SpecialProductPresenter, SpecialProductModel> implements SpecialProductContract.View {

    @Bind(R.id.tbv_special_product)
    TitleBarView mTbvProduct;
    @Bind(R.id.bcd_product)
    BookCountDown mBcdProduct;
    @Bind(R.id.tv_product_sell_count)
    TextView mTvProductSellCount;
    @Bind(R.id.rb_send_time1)
    RadioButton mRbSendTime1;
    @Bind(R.id.rb_send_time2)
    RadioButton mRbSendTime2;
    @Bind(R.id.rb_send_time3)
    RadioButton mRbSendTime3;
    @Bind(R.id.rb_send_time4)
    RadioButton mRbSendTime4;
    @Bind(R.id.rb_send_time5)
    RadioButton mRbSendTime5;
    @Bind(R.id.rg_send_time)
    RadioGroup mRgSendTime;
    @Bind(R.id.cgv_product)
    CustomGridView mCgvProduct;
    @Bind(R.id.tv_special_buy)
    TextView mTvSpecialBuy;
    @Bind(R.id.ll_special_product_top_date)
    LinearLayout mLlSpecialProductTopDate;
    @Bind(R.id.rg_special_product_send_top_time)
    RadioGroup mRgSpecialProductSendTopTime;
    @Bind(R.id.rb_special_product_send_top_time1)
    RadioButton mRbSpecialProductSendTopTime1;
    @Bind(R.id.rb_special_product_send_top_time2)
    RadioButton mRbSpecialProductSendTopTime2;
    @Bind(R.id.rb_special_product_send_top_time3)
    RadioButton mRbSpecialProductSendTopTime3;
    @Bind(R.id.rb_special_product_send_top_time4)
    RadioButton mRbSpecialProductSendTopTime4;
    @Bind(R.id.rb_special_product_send_top_time5)
    RadioButton mRbSpecialProductSendTopTime5;
    @Bind(R.id.osv_special_product)
    ObservableScrollView mOsvSpecialProduct;
    @Bind(R.id.rl_special_product_BookCountDown)
    RelativeLayout mRlSpecialProductBookCountDown;
    private String spiltDate = new Date().getYear() + 1900 + "-";
    public static String chooseDate = "";

    private String[] weekList = {"", "周日", "周一", "周二", "周三", "周四", "周五", "周六"};

    private List<RadioButton> rbTopTimeList = new ArrayList<RadioButton>();     //顶部选择日期
    private List<RadioButton> rbTimeList = new ArrayList<RadioButton>();

    private int curPosition;        //当前被选择日期的位置
    private List<WeekdayState> weekdayStates;

    private SpecialProductAdapter adapter;

    private List<Product> dataList = new ArrayList<>();

    private ProductClasses productClasses;

    private ProductCartDao mProductCartDao;

    @Override
    public int getLayoutId() {
        return R.layout.activity_special_product;
    }

    @Override
    public void initView() {

        rbTopTimeList.add(mRbSpecialProductSendTopTime1);
        rbTopTimeList.add(mRbSpecialProductSendTopTime2);
        rbTopTimeList.add(mRbSpecialProductSendTopTime3);
        rbTopTimeList.add(mRbSpecialProductSendTopTime4);
        rbTopTimeList.add(mRbSpecialProductSendTopTime5);
        rbTimeList.add(mRbSendTime1);
        rbTimeList.add(mRbSendTime2);
        rbTimeList.add(mRbSendTime3);
        rbTimeList.add(mRbSendTime4);
        rbTimeList.add(mRbSendTime5);


        productClasses = (ProductClasses) getIntent().getSerializableExtra("product");

        mProductCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();

        mTbvProduct.setTitleNoRight(productClasses.getClassName());
        mTbvProduct.setBack(this);

        mTvProductSellCount.setText(productClasses.getSellcount() + "");

        initBookCountDown(productClasses.getClosetime());

        mTvSpecialBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mProductCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();
                if ((mProductCartDao.loadAll() == null ||
                        mProductCartDao.loadAll().size() == 0)) {
                    T.show("购物车为空,请添加商品");
                    return;
                }
                Intent intent = new Intent(SpecialProductActivity.this, UserCartActivity.class);
                startActivity(intent);
            }
        });

        mOsvSpecialProduct.setScrollViewListener(new ScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                //选择日期顶部悬浮
                if (y >= mRlSpecialProductBookCountDown.getHeight()) {
                    mLlSpecialProductTopDate.setVisibility(View.VISIBLE);
                    rbTopTimeList.get(curPosition).setChecked(true);
                } else {
                    mLlSpecialProductTopDate.setVisibility(View.GONE);
                    rbTimeList.get(curPosition).setChecked(true);
                }
                chooseDate = weekdayStates.get(curPosition).getWdate();
            }
        });
    }

    @Override
    public void showProductState(ProductState productState) {
        weekdayStates = productState.getData();

        //已经打烊，选择日期不可点击
        if (mBcdProduct.getTimeComplete()) {
            setRadioButtonFalse();
            return;
        }

        analyseWeek(mRbSendTime1, 0);
        analyseWeek(mRbSendTime2, 1);
        analyseWeek(mRbSendTime3, 2);
        analyseWeek(mRbSendTime4, 3);
        analyseWeek(mRbSendTime5, 4);
        analyseWeek(mRbSpecialProductSendTopTime1, 0);
        analyseWeek(mRbSpecialProductSendTopTime2, 1);
        analyseWeek(mRbSpecialProductSendTopTime3, 2);
        analyseWeek(mRbSpecialProductSendTopTime4, 3);
        analyseWeek(mRbSpecialProductSendTopTime5, 4);

        presenter.getProductDetail(productClasses.getClassId() + "");
    }

    @Override
    public void showProductDetail(ProductDetail productDetail) {
        dataList = productDetail.getData();
        adapter = new SpecialProductAdapter(context, dataList);
        mCgvProduct.setAdapter(adapter);
        if (mBcdProduct.getTimeComplete()) {
            adapter.setClickAble(false);
        } else {
            adapter.setClickAble(true);
        }
    }

    private void initBookCountDown(String closeTime) {
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            Long now = System.currentTimeMillis();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DATE);
            String dates = year + "-" + (month < 10 ? "0" + month : month)
                    + "-" + (day < 10 ? "0" + day : day) + " " + closeTime;
            Date date = df.parse(dates);
            if (date.getTime() < now) {
                mBcdProduct.setTime(0, 0, 0, true);
                return;
            }
            Long diff = date.getTime() - now;
            Long days = diff / (1000 * 60 * 60 * 24);
            Long hours = (diff - days * (1000 * 60 * 60 * 24))
                    / (1000 * 60 * 60);
            Long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours
                    * (1000 * 60 * 60))
                    / (1000 * 60);
            Long second = (diff - days * (1000 * 60 * 60 * 24) - hours
                    * (1000 * 60 * 60) - minutes * (1000 * 60)) / (1000);

            mBcdProduct.setTime(hours.intValue(), minutes.intValue(),
                    second.intValue(), true);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置 不可选中
     *
     * @param rb_time
     */
    private void setTimeDisableClick(RadioButton rb_time) {
        rb_time.setEnabled(false);
        Drawable drawable = getResources().getDrawable(R.drawable.ic_product_expired);
        // / 这一步必须要做,否则不会显示.
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        rb_time.setCompoundDrawables(null, null, null, drawable);
        rb_time.setCompoundDrawablePadding(DensityUtil.dp2px(context, 3));
    }

    private void analyseWeek(RadioButton rb_time, int positon) {
        if (weekdayStates.size() > positon) {
            // 设置日期
            rb_time.setTag(positon);
            rb_time.setText(weekList[weekdayStates.get(positon).getWday()]
                    + "\n"
                    + weekdayStates.get(positon).getWdate()
                    .replaceAll(spiltDate, ""));
            if (weekdayStates.get(positon).getState().equals("1")) {// 不可选
                setTimeDisableClick(rb_time);
            } else if (weekdayStates.get(positon).getState().equals("2")) {// 选中
                rb_time.setChecked(true);
                curPosition = positon;
                // 设置选中的日期
                chooseDate = weekdayStates.get(positon).getWdate();
            } else if (weekdayStates.get(positon).getState().equals("3")) {// 可选
            } else {

            }
            rb_time.setVisibility(View.VISIBLE);
        } else {
            rb_time.setVisibility(View.INVISIBLE);
        }

        rb_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDate = weekdayStates.get(positon).getWdate();
                adapter.notifyDataSetChanged();
                curPosition = positon;
            }
        });
    }

    //设置所有日期选择不可点击
    private void setRadioButtonFalse() {
        for (RadioButton rb : rbTimeList
                ) {
            rb.setEnabled(false);
        }
        for (RadioButton rb : rbTopTimeList
                ) {
            rb.setEnabled(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter = new SpecialProductAdapter(context, dataList);
        mCgvProduct.setAdapter(adapter);
    }

}

